Ext.define('appmod.controller.knowledge.Startup', {
    extend: 'Ext.app.Controller',
    
   	stores:[
		'knowledge.category.Tree',
		'knowledge.content.BigView',
		'knowledge.FileFormat',
		'knowledge.content.colligation.ListAll',			
		'knowledge.CurrentUserCategoryPerm'		
   	],   

    views: [
		'knowledge.TreeDashboard',
		'knowledge.category.Form',			
		'knowledge.content.BigView',
		'knowledge.content.onlineview.PicView',
		'knowledge.content.upload.MultiFile',		
		'knowledge.content.UploadFileForm',
		'knowledge.content.BindingColligationForm'
    ],
	

    refs: [
		{ref: 'knowledgeTree', selector: 'knowledge-treedashboard knowledge-tree-grid'},
		{ref:'mainContentPanel' ,selector:'knowledge-treedashboard tabpanel' },
		{ref: 'knowledgeCateTreeGrid', selector: 'knowledge-tree-grid'},		
		{ref:'mainDashboardPanel' ,selector:'knowledge-treedashboard'},
		{ref:'contentBigView' ,selector:'knowledge-treedashboard knowledge-content-bigview'},
		{ref:'comboFileFormat' ,selector:'knowledge-treedashboard knowledge-content-bigview combobox'}
    ],	

    init: function() {
		var me = this;

    	me.control({

			'knowledge-treedashboard knowledge-tree-grid' : {
				select: {
					fn:me.selectItem,
					scope:me
				}
			},			
			'knowledge-treedashboard button[action=delete]': {
				click:{
					fn:me.showDeleteItemDialog,
					scope:me
				}
			},
			'knowledge-treedashboard knowledge-content-bigview button[action=uploadMultiFiles]': {
				click:{
					fn:me.showUploadMultiFilesDialog,
					scope:me
				}
			},
			'knowledge-treedashboard knowledge-content-bigview button[action=deleteFiles]': {
				click:{
					fn:me.showDelFilesDialog,
					scope:me
				}
			},
			'knowledge-treedashboard knowledge-content-bigview button[action=bindColligation]': {
				click:{
					fn:me.showBindColligationDialog,
					scope:me
				}
			},			
			'knowledge-treedashboard knowledge-content-bigview dataview' : {
				itemdblclick: {
					fn:me.openDataView,
					scope:me
				}
			},
			'knowledge-treedashboard knowledge-content-bigview combobox' : {
				change: {
					fn:me.changeFileFormat,
					scope:me
				}
			},			
			'knowledge-treedashboard button[action=addCategory]' : {
				click: {
					fn:me.showCategoryAddingForm,
					scope:me
				}
			}															
    	});
    },

	
	/**
	 * load main compont in this controller to framework container
	 */
	loadInitComp : function() {
		var me = this;
		// --- defined store ---
		var treeCategory = me.getKnowledgeCategoryTreeStore();
		
		var stores = {
			'category' : treeCategory
		};

		var mainPanel = Ext.create('appmod.view.knowledge.TreeDashboard' , {
			region : 'center',
			stores : stores,
			border:false,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	

	// --- use this app lication
	onLaunch:function(app) {
		var me = this;
		
		// --- init data binding ----
		var dsFormatStore = me.getKnowledgeFileFormatStore();
		var comboFileFormat = me.getComboFileFormat();
		comboFileFormat.bindStore( dsFormatStore );		
		
		// --- init component security ---
		var mainDashboardPanel = me.getMainDashboardPanel();
		var btnUploadMultiFiles = mainDashboardPanel.down('button[action=uploadMultiFiles]');
		var btnDeleteFiles = mainDashboardPanel.down('button[action=deleteFiles]');
		var btnAddCate =  mainDashboardPanel.down('button[action=addCategory]');
		var btnDelCate =  mainDashboardPanel.down('button[action=deleteCategory]');

		
		btnUploadMultiFiles.disable();
		btnDeleteFiles.disable();
		btnAddCate.disable();
		btnDelCate.disable();
		

	},
	
	selectItem:function(rowModel, record, index, eOpts) {
		var me = this;
		// --- update perm category ----
		var dsCurrentUserCatePerms = me.getKnowledgeCurrentUserCategoryPermStore();
		dsCurrentUserCatePerms.reload();
		
		// --- get current record ---
		var mainDashboardPanel = me.getMainDashboardPanel();
		var userPerms = dsCurrentUserCatePerms.query('categoryId' ,  record.getId() );
		var permData = userPerms.first();
		
		// --- add permission logic ---
		if (permData != null) {
			var btnUploadMultiFiles = mainDashboardPanel.down('button[action=uploadMultiFiles]');
			var btnDeleteFiles = mainDashboardPanel.down('button[action=deleteFiles]');
			
			var btnAddCate =  mainDashboardPanel.down('button[action=addCategory]');
			var btnDelCate =  mainDashboardPanel.down('button[action=deleteCategory]');
			
				
			var isAdmin = permData.get('isAdmin');
			if (isAdmin == 1) {
				
				// --- enable all button ---
				btnUploadMultiFiles.enable();
				btnDeleteFiles.enable();
				btnAddCate.enable();
				btnDelCate.enable();
				
			} else {
				var kmAdding = permData.get('kmAdding');
				var kmEditing = permData.get('kmEditing');
				var kmPost = permData.get('kmPost');
				var kmDeleting = permData.get('kmDeleting');
				
				var cateAdding = permData.get('cateAdding');
				var cateEditing = permData.get('cateEditing'); 
				var cateDeleting = permData.get('cateDeleting');
				
				// --- enable/disable button ---
				if (kmAdding || kmEditing) {
					btnUploadMultiFiles.enable();
				} else {
					btnUploadMultiFiles.disable();					
				}
				
				if (kmDeleting) {
					btnDeleteFiles.enable();
				} else {
					btnDeleteFiles.disable();
				}
				
				if ( cateAdding || cateEditing) {
					btnAddCate.enable();
				} else {
					btnAddCate.disable();
				}
				
				if (cateDeleting) {
					btnDelCate.enable();
				} else {
					btnDelCate.disable();
				}
				
				
			}
		}

		var picStore = me.getKnowledgeContentBigViewStore();

		var comboFileFormat = me.getComboFileFormat();
		var selValue = comboFileFormat.getValue();
		if (!selValue) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请选择显示的格式',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return;				
		}
		
		
		// --- defind and load object ---
		var proxy = picStore.getProxy();
		proxy.extraParams = {
			categoryId:record.getId(),
			fileFormat:selValue
		}
		picStore.load();
		
		var contentBigView = me.getContentBigView();
		contentBigView.bindStore(picStore);


	},
	
	showDeleteItemDialog: function(){
	
		var me = this;
		var mainContentPanel = me.getMainContentPanel();
		var currentPanel = mainContentPanel.down('knowledge-content-bigview');
		var selMod = currentPanel.getView().getSelectionModel();
		var recs = selMod.getSelection();
		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0; i < recs.length; i++) {
			if (removeRecs.length != 0) {
				removeRecs += ",";
			}
			
			removeRecs += recs[i].get('fileName');
			console.info( removeRecs );
		}
		Ext.MessageBox.confirm('确认', '确定要删除信息及文件: "' + removeRecs + '"?', me.confirmDelContent, me);
	
	},
	
	
	confirmDelContent:function() {
		
		
	},
	
	showUploadMultiFilesDialog:function() {
		me = this;

		var knowledgeTree = me.getKnowledgeTree();
		var selMod = knowledgeTree.getSelectionModel();
		var recs = selMod.getSelection();

		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择分类',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		var categoryId = recs[0].getId();

		var win = null;
		// ---- get current location url ---
		
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '附件',
				closable : true,
				width : 500,
				height : 480,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					base_setting : {
						upload_url:'../../data/upload/attachment.act',
						post_params: {
							'categoryId':categoryId
						}
					},
					xtype : 'knowledge.content.upload.multifile',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '上 传',
							action:'uploadFiles'
        				},
				        {
            				text: '关 闭',
							action:'closeWindow'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var formView = win.down("knowledge-content-upload-multifile");
		formView.on('uploadSuccess' ,me.uploadSuccess , me , {
			window : win
		});
		

		var uploadBtn = win.down('button[action="uploadFiles"]');
		uploadBtn.on("click",me.uploadFiles , me , {
			window : win
		});

		var closeBtn = win.down('button[action="closeWindow"]');
		closeBtn.on("click",me.closeUploadWindow , me , {
			window : win
		});
		
		// --- binding category ---

		if ( !win.isVisible() ) {
			win.show();
		}		
		
	},
	
	uploadFiles:function(btn , event , eOpts) {
		
		var upWin = eOpts.window;
		
		var swfUploadBtn = upWin.down('swfupload-button');
		
		var multiFileList = upWin.down('knowledge-content-upload-multifile');
		var dsMultiFile = multiFileList.getStore();
		
		var recs = dsMultiFile.query('uploadStatus' , SWFUpload.FILE_STATUS.QUEUED );
		// --- get the queued files ---
		if (recs.getCount() == 0 ) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '没有需要上传的文件',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});			
			return ;
		}
		else {
			// --- upload file ---
			swfUploadBtn.setUploadAllQueued(true);
			var swfUploadComp = swfUploadBtn.getSWFUpload();
			swfUploadComp.startUpload();
		}

				
	},
	
	closeUploadWindow:function(btn , event , eOpts) {
		// --- clear old upload
		var upWin = eOpts.window;
		var swfUploadBtn = upWin.down('swfupload-button');
		var multiFileList = upWin.down('knowledge-content-upload-multifile');
		var dsMultiFile = multiFileList.getStore();
		
		var swfUploadComp = swfUploadBtn.getSWFUpload();
		swfUploadComp.stopUpload();		

		//var selectedFiles = swfUploadBtn.getSelectedFiles();

		// --- get file from store ---
		for (var i = dsMultiFile.getCount() - 1 ; i >= 0  ; i--) {
			var rec = dsMultiFile.getAt(i);
        	var recId = rec.getId();
				
			if ( rec.getId() ) {
				swfUploadComp.cancelUpload(  rec.getId() );
				// --- remove current file ---
				dsMultiFile.remove(rec);
			}	
		}

		var destroy = swfUploadComp.destroy();
		if (destroy && upWin && upWin.isVisible() ) {
			upWin.close();
		}

		
		
	},
	
	uploadSuccess:function(btn , event , eOpts) {
		var me = this;
		var bigPanel = me.getContentBigView();
		var currentView =  bigPanel.getView();
		
		var currentStore = currentView.getStore();
		if (currentStore) {
			currentStore.reload();
		}

	},
	
	openDataView:function(thisVew, record, item, index, event, eOpts) {

		var me = this;
		
		// --- check the record ext type ---
		var ext = record.get('extformat');

		var fileExt =  record.get('ext');

		var popupView = {
			padding : 5,
			xtype:'panel',
			region:'center'
		}
		
		var width = 500;
		var height = 480;
		
		var preview = 0; // 0 = open url direct ; 1 = preview 
						
		if ('img' == ext) {
			// --- use defined view 
			popupView =  {
				padding : 5,
				xtype:'knowledge.content.onlineview.picview',
				region:'center',
				src:record.get('bigPicUrl')
			}
			width = 500;
			height = 400;
			preview = 1;
		}
		
		else if (
			'xls'==fileExt 
			|| 'doc' == fileExt
			 ) {
			 	
			if (!Ext.isIE) {
				Ext.MessageBox.show({
	        		title: "提示",
	        		msg: '在线预览只支持IE 7 - 9',
	        		buttons: Ext.MessageBox.OK,
	        		icon: Ext.MessageBox.WARNING
	       		});					
				return ;
			}	
				
			var url = '../../data/onlineviewer/ieviewer.htm?';
			url+='fileName='+encodeURI ( record.get('bigPicUrl') );
			url+='&ext='+fileExt;
			popupView =  {
				padding : 5,
				xtype:'knowledge.content.onlineview.picview',
				region:'center',
				src:url
			}
			width = 800;
			height = 600;
			preview =  1;			
		}
		else if (
			'avi'==fileExt ||
			'mp4'==fileExt
			 ) {
			 	
			if (!Ext.isIE) {
				Ext.MessageBox.show({
	        		title: "提示",
	        		msg: '在线预览只支持IE 7 - 9',
	        		buttons: Ext.MessageBox.OK,
	        		icon: Ext.MessageBox.WARNING
	       		});					
				return ;
			}					
				
			var url = '../../data/onlineviewer/video/ieviewer.htm?';
			url+='fileName='+encodeURI ( record.get('bigPicUrl') );
			url+='&ext='+fileExt;
			url+='&onlineView=0';
		
			popupView =  {
				padding : 5,
				xtype:'knowledge.content.onlineview.picview',
				region:'center',
				src:url
			}
			width = 800;
			height = 600;
			preview =  1;			
		}		
		else {
			var url = record.get('bigPicUrl');
			
			// --- popup the url ---
			window.open (url,"mywindow"); 
			
			return ;		
		}

		var win = null;
		
		// --- build new form ---
		if (preview == 1 && !win) {
			win = new Ext.create('widget.window', {
				title : '在线浏览',
				closable : true,
				width : width,
				height : height,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[popupView],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '关 闭',
							action:'closeWindow'
        				}
				    ]
				}]	
			});
		}

		// --- find form ---
		var btnCloseWindow = win.down('button[action="closeWindow"]');
		btnCloseWindow.on("click",me.closeOnlineView , me , {
			window : win
		});	
		
		// --- find form ---
		if ( !win.isVisible() ) {
			win.show();
		}	

	},
	
	closeOnlineView:function(btn , event , eOpts) {

		var currentWin = eOpts['window'];
		
		// --- check ----
		var panel = currentWin.down('knowledge-content-onlineview-picview');

		var objectWin = panel.getWin();
		if (objectWin.Office) {
			objectWin.Office.close();
		}

		if (currentWin.isVisible() ) {

			currentWin.hide();
		}

	},
		
	
	showCategoryAddingForm:function() {
		var me = this;
		
		// --- get the parent id ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();


		// --- define category store ---
		var dsCategoryTree = me.getKnowledgeCategoryTreeStore();
	
		var fieldStores = {
			'dsParentCategory' : dsCategoryTree
		};
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '信息分类',
				closable : true,
				width : 250,
				height : 160,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.category.form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addCategory'
        				},{
            				text: '清 空 ',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-category-form");
		
		if (recs && recs.length == 1) {
			// --- reset parent id ---
			var ffParentId = form.down('treepicker[name=parentId]');
			ffParentId.setValue(recs[0].getId());
		}
		
		var saveBtn = win.down('button[action="addCategory"]');
		saveBtn.on("click",me.saveAddCategory , me , {
			window : win
		});

		var resetBtn = win.down('button[action="reset"]');
		resetBtn.on("click",me.resetCategoryForm , me , {            
			window : win                                             
		});                                                          

		if ( !win.isVisible() ) {
			win.show();
		}		
	},
	
	saveAddCategory:function(btn, event, eOpts) { 
		var me = this;

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('knowledge-category-form');

		var form = formPanel.getForm();
		
		// --- get submit form value ---
		var submitValues = form.getValues();
		// --- get list panel and reflash ---
		var treeGrid = me.getKnowledgeCateTreeGrid();

		form.submit({
			url:'../../data/resource/knowledge/category/submit_addcate.json',
			success:function(form , action) {
				 Ext.Msg.alert('成功', action.result.msg);
				 if (upWin.isVisible()) {
				 	upWin.close();
				 }
				 
				 var store = treeGrid.getStore();
				 if (store) {
				 	store.reload();
				 }
				 
			},
			failure: function(from, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});		
	},
	
	changeFileFormat:function(objectSelf, newValue, oldValue, eOpts) {
		var me = this;
		var contentBigView = me.getContentBigView();
		var picStore = me.getKnowledgeContentBigViewStore();
		
		// --- defind and load object ---
		var proxy = picStore.getProxy();

		proxy.extraParams['fileFormat'] = newValue;
		picStore.load();
		

		contentBigView.bindStore(picStore);		
	},
	
	showDelFilesDialog:function(btn, event, eOpts) {
		var me = this;

		var defListView = me.getContentBigView();	
		var selModel = defListView.getView().getSelectionModel();
		var recs = selModel.getSelection();

		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一份文件',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}

		var removeRecs = "";
		for (var i = 0 ; i < recs.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			removeRecs += recs[i].get('name');
		}
		
		Ext.MessageBox.confirm('确认', '肯定要删除文件: "'+removeRecs+'"?',me.confirmDeletedFiles , me);		
	},
	
	
	confirmDeletedFiles:function(confirm) {
		var me = this;
		var defListView = me.getContentBigView();	
		var selModel = defListView.getView().getSelectionModel();
		var recs = selModel.getSelection();
		
		if (confirm == "no") {
			return;
		}

		var jsonObj = [];
		for (var i = 0 ; i < recs.length ; i++) {
			jsonObj.push(recs[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/knowledge/content/submit_deletefiles.json',
				method:'post',   
				jsonData:jsonObj,
				success: function(response, opts) {

					var listView = defListView.getView();
					// --- update load ---
					listView.getStore().reload();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
					alert("error alert for delete file !");
		
				}
			});

			
		} catch (e) {
			Ext.log({
				msg:'error : ' + e
			})
		}	
	},
	
	showBindColligationDialog:function(btn, event, eOpts) {
		var me = this;

		var currentPanel = me.getContentBigView();
		var selMod = currentPanel.getView().getSelectionModel();
		var recs = selMod.getSelection();

		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择附件',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- get the current knowledge ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var cateSelMod = knowledgeCateTreeGrid.getSelectionModel();
		var cateRecs = cateSelMod.getSelection();
		
		var cateId = cateRecs[0].getId();
		
		var dsCollListAll = me.getKnowledgeContentColligationListAllStore();
 		var proxy = dsCollListAll.getProxy();
		proxy.extraParams = {
			categoryId:cateId
		}
		dsCollListAll.reload();
		
		// --- bind multi select store ---
				
	
		var fieldStores = {
			'dsColligation' : dsCollListAll
		};			
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '附件设定',
				closable : true,
				width : 500,
				height : 400,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.content.bindingcolligationform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '指 定',
							action:'bindColligation'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-content-bindingcolligationform");
		
		if (recs && recs.length > 0) {
			// --- reset parent id ---
			var attachmentFields  = form.down('multiselect[name=selectedAttachment]');
			var store = attachmentFields.getStore();
			var inputValues = [];
			for (var i = 0 ; i < recs.length ; i++) {
				var rec = recs[i];
				inputValues.push( rec.getId() );

				var model = Ext.create('appmod.model.SelectItemModel', {
				    id:rec.getId(),
					name : rec.get('name')
				});
				
				store.add(model);
			}
			attachmentFields.setValue(inputValues); 
		}
		
		var saveBtn = win.down('button[action="bindColligation"]');
		saveBtn.on("click",me.bindColligation , me , {
			window : win
		});

		if ( !win.isVisible() ) {
			win.show();
		}			
	},
	
	bindColligation:function(btn , event , eOpts) {
		var me = this;

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('knowledge-content-bindingcolligationform');

		var form = formPanel.getForm();
		
		// --- get submit form value ---
		var submitValues = form.getValues();
		
		// --- get list panel and reflash ---
		var currentPanel = me.getContentBigView();
		var currentView = currentPanel.getView()

		form.submit({
			url:'../../data/resource/knowledge/attachment/submit_bindcolligation.json',
			success:function(form , action) {
				 Ext.Msg.alert('成功', action.result.msg);
				 if (upWin.isVisible()) {
				 	upWin.close();
				 }
				 
				 var store = currentView.getStore();
				 if (store) {
				 	store.reload();
				 }
				 
			},
			failure: function(from, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});				
	}		
});